const express = require('express');
const router = express.Router();
const upload = require('../multer/multer')
const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient()
const { generateUserId } = require('../utils/uuid')
const { hashPassword, checkPassword } = require('../utils/bcrypt')
const { generateToken, parseToken } = require('../utils/token')

const { returnUserData } = require('../utils/prismaData');
// 封装返回的数据



/* GET home page. */


// loginJWT
router.post('/loginJWT', upload.none(), async (req, res) => {
  const token = req.headers.authorization.split(' ')[1]
  const tokenData = await parseToken(token)
  if (!tokenData) {
    return res.status(401).send({ msg: '登录过期' });
  }
  const { id, user } = tokenData
  const userData = await prisma.user.findUnique({
    where: {
      id: id,
      name: user
    }
  })
  if (userData === null) {
    return res.status(404).send({ msg: '用户不存在' });
  }
  res.status(200).send(returnUserData(userData))
})

// login
router.post('/login', upload.none(), async (req, res) => {
  // 发送的数据
  const { username, password: psd } = req.body
  if (username === undefined || psd === undefined) {
    return res.status(403).send({ msg: '数据不合法' });
  }
  try {
    const userData = await prisma.user.findUnique({
      where: {
        name: username
      }
    })
    if (userData === null) {
      return res.status(404).send({ msg: '用户名不存在' });
    }
    // 验证密码
    const match = await checkPassword(psd, userData.password)
    if (!match) {
      return res.status(401).send({ msg: '密码错误' });
    }
    // 成功登录
    res.status(200).send(returnUserData(userData))
  } catch (error) {
    console.log(error);
  }
})


// regist
router.post('/regist', upload.none(), async (req, res) => {
  // 发送的数据
  const { username, password, confirm } = req.body
  if (password !== confirm) return res.status(403).send({ msg: '密码和确认密码不一致' })
  if (username === undefined || password === undefined) return res.status(403).send({ msg: '数据不合法' })

  if (username.length >= 20 || password.length >= 20) return res.status(403).send({ msg: '数据过长,20字符以内' })

  const userData = await prisma.user.findUnique({
    where: {
      name: username
    }
  })
  if (userData !== null) return res.status(403).send({ msg: '用户名已存在' })

  // 允许创建新账号
  const generateId = generateUserId()
  const pass = await hashPassword(password)
  const newUser = await prisma.user.create({
    data: {
      id: generateId,
      name: username,
      password: pass,
      img: 'images/logo.svg'
    }
  })
  if (newUser === null) return res.status(403).send({ msg: '插入错误' })

  const { id, name: user, img } = newUser
  const token = generateToken({ id: generateId, username: username })
  res.status(200).send({ id, user, img, token })
})

module.exports = router;
